<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
    </head>
    <body>
        <!-- 利用了闭包保存了timer变量。延长了其生命周期 -->
        <!-- 防抖 -->
        <!-- 第一次立即执行 -->
        <script>
            function debouce(fn, delay, immediate) {
                let timer;
                return function (...args) {
                    if (timer) clearTimeout(timer);
                    if (immediate) {
                        let fastRun = !timer;
                        timer = setTimeout(() => {
                            timer = null;
                        }, delay);
                        fn.apply(this, args);
                    } else {
                        timer = setTimeout(() => {
                            fn.apply(this, args);
                        }, delay);
                    }
                };
            }

            function throller(fn, delay) {
                let timer = null;
                return function (...args) {
                    if (!timer) {
                        timer = setTimeout(() => {
                            fn.apply(this, args);
                            timer = null;
                        });
                    }
                };
            }
        </script>
    </body>
</html>
